package mysql

import (
	"database/sql"
	"fmt"
	"log"
	"time"

	_ "github.com/go-sql-driver/mysql"
)

const (
	PORT     = 3306
	SERVER   = "localhost"
	USERNAME = "root"
	PASSWORD = "root"
	NETWORK  = "tcp"
	DATABASE = "test"
)

var connStr string
var db *sql.DB

func Init() {
	connStr = fmt.Sprintf("%s:%s@%s(%s:%d)/%s", USERNAME, PASSWORD, NETWORK, SERVER, PORT, DATABASE)
}

func Query(query string) (map[int]map[string]string, error) {
	// 连接数据库
	mysql, err := sql.Open("mysql", connStr)
	defer mysql.Close()
	mysql.SetConnMaxLifetime(100 * time.Second) //最大连接周期，超过时间的连接就close
	mysql.SetMaxOpenConns(100)                  //设置最大连接数
	mysql.SetMaxIdleConns(16)                   //设置闲置连接数

	if err != nil {
		log.Fatal(err)
	}

	// 执行查询
	rows, err := mysql.Query(query)
	if err != nil {
		log.Fatal(err)
		return make(map[int]map[string]string), err
	}

	cols, _ := rows.Columns()

	//这里表示一行所有列的值，用[]byte表示

	vals := make([][]byte, len(cols))

	//这里表示一行填充数据

	scans := make([]interface{}, len(cols))

	//这里scans引用vals，把数据填充到[]byte里

	for k, _ := range vals {

		scans[k] = &vals[k]

	}

	i := 0

	result := make(map[int]map[string]string)

	for rows.Next() {
		//填充数据

		rows.Scan(scans...)

		//每行数据

		row := make(map[string]string)

		//把vals中的数据复制到row中

		for k, v := range vals {
			key := cols[k]

			//这里把[]byte数据转成string

			row[key] = string(v)

		}

		//放入结果集

		result[i] = row

		i++

	}

	return result, err
}
